import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Form, Input, Button, ImageUploader, Toast, Dialog, TextArea, Space, NavBar,
  Image
} from 'antd-mobile';
import { PictureOutline, VideoOutline, CloseOutline, EnvironmentOutline } from 'antd-mobile-icons';
import { createTravel, checkLoginStatus, uploadFileToOSS } from '../../services/api';
import styles from './index.module.css';
import '../../styles/responsive.css'; // 导入响应式样式

// 旅游主题色
const THEME_COLORS = {
  primary: '#27408b',     // 主色调：有质感的深蓝色
  secondary: '#3498db',   // 次要色：湖水蓝
  accent: '#f39c12',      // 强调色：温暖的橙色
  background: '#f9f9f9',  // 背景色：浅灰色
  text: '#2c3e50',        // 文本色：深蓝灰色
  lightText: '#7f8c8d',   // 浅色文本：灰色
};

// 图片压缩配置
const imageUploaderProps = {
  multiple: true,
  maxCount: 9,
  maxSize: 10 * 1024 * 1024, // 10MB
  accept: 'image/*',
  showUpload: true,
  onFailed: (error: any) => {
    if (error.reason === 'file-type-error') {
      Toast.show('请上传正确格式的图片');
    } else if (error.reason === 'file-size-exceed') {
      Toast.show('图片大小不能超过10MB');
    }
  },
};

// 视频上传配置
const videoUploaderProps = {
  maxCount: 1,
  maxSize: 100 * 1024 * 1024, // 100MB
  accept: 'video/*',
  multiple: false,
  showUpload: true,
  onFailed: (error: any) => {
    if (error.reason === 'file-type-error') {
      Toast.show('请上传正确格式的视频');
    } else if (error.reason === 'file-size-exceed') {
      Toast.show('视频大小不能超过100MB');
    }
  },
};


interface TravelFormValues {
  title: string;
  content: string;
  location?: string;
  images: string[];
  video?: string;
}

const PublishPage: React.FC = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [images, setImages] = useState<{ url: string }[]>([]);
  const [video, setVideo] = useState<{ url: string } | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [formError, setFormError] = useState<{ [key: string]: string }>({});

  // 检查登录状态
  useEffect(() => {
    const checkLogin = async () => {
      try {
        const isLoggedIn = await checkLoginStatus();
        if (!isLoggedIn) {
          Toast.show({
            content: '请先登录',
            afterClose: () => {
              navigate('/auth/login');
            },
          });
        }
      } catch (error) {
        console.error('检查登录状态失败:', error);
        Toast.show({
          content: '网络错误，请重试',
          afterClose: () => {
            navigate('/auth/login');
          },
        });
      }
    };

    checkLogin();
  }, [navigate]);

  // 处理图片上传
  const handleImageUpload = async (file: File) => {
    try {
      Toast.show({
        icon: 'loading',
        content: '正在上传图片...',
        duration: 0,
      });

      // 使用阿里云OSS上传图片
      const result = await uploadFileToOSS(file);

      // 上传成功后关闭提示
      Toast.clear();

      // 返回图片URL
      return { url: result.url };
    } catch (error) {
      Toast.clear();
      Toast.show({
        icon: 'fail',
        content: '图片上传失败，请重试',
      });
      throw error;
    }
  };

  // 处理视频上传
  const handleVideoUpload = async (file: File) => {
    try {
      Toast.show({
        icon: 'loading',
        content: '正在上传视频...',
        duration: 0,
      });

      // 使用阿里云OSS上传视频
      const result = await uploadFileToOSS(file);

      // 上传成功后关闭提示
      Toast.clear();

      // 返回视频URL
      return { url: result.url };
    } catch (error) {
      Toast.clear();
      Toast.show({
        icon: 'fail',
        content: '视频上传失败，请重试',
      });
      throw error;
    }
  };

  // 表单验证
  const validateForm = (values: TravelFormValues) => {
    const errors: { [key: string]: string } = {};

    if (!values.title || values.title.trim() === '') {
      errors.title = '请输入游记标题';
    }

    if (!values.content || values.content.trim() === '') {
      errors.content = '请输入游记内容';
    }

    if (!images.length) {
      errors.images = '请至少上传一张图片';
    }

    setFormError(errors);
    return Object.keys(errors).length === 0;
  };

  // 提交表单
  const onFinish = async (values: TravelFormValues) => {
    if (!validateForm(values)) {
      return;
    }

    try {
      setSubmitting(true);

      // 准备提交数据
      const travelData = {
        title: values.title,
        content: values.content,
        location: values.location || '',
        images: images.map(img => img.url),
        video: video ? video.url : null,
        author: {
          _id: 'user123', // 这里应该是实际的用户ID
          nickname: '测试用户', // 这里应该是实际的用户昵称
          avatar: 'https://example.com/avatar.jpg' // 这里应该是实际的用户头像
        }
      };

      // 提交游记数据
      const response = await createTravel(travelData);

      if (response.code === 0) {
        Toast.show({
          icon: 'success',
          content: '发布成功，等待审核',
        });
        navigate('/');
      } else {
        throw new Error(response.message || '发布失败');
      }
    } catch (error) {
      console.error('发布游记失败:', error);
      Toast.show({
        icon: 'fail',
        content: '发布失败，请重试',
      });
    } finally {
      setSubmitting(false);
    }
  };

  // 返回上一页
  const handleBack = () => {
    if (form.isFieldsTouched() || images.length > 0 || video) {
      Dialog.confirm({
        content: '离开页面将丢失已编辑的内容，确定要离开吗？',
        onConfirm: () => {
          navigate(-1);
        },
      });
    } else {
      navigate(-1);
    }
  };

  return (
    <div style={{
      backgroundColor: THEME_COLORS.background,
      minHeight: '100vh',
      padding: '0 0 20px 0',
      width: '100%',
      maxWidth: '100%',
      overflow: 'hidden',
      boxSizing: 'border-box'
    }}>
      <NavBar
        onBack={handleBack}
        style={{
          backgroundColor: THEME_COLORS.primary,
          color: 'white',
          padding: '12px 16px',
          fontSize: '18px',
          fontWeight: 'bold',
          
          boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
          width: '100%'
        }}
      >
        <span style={{ fontSize: '18px', fontWeight: 'bold' }}>发布游记</span>
      </NavBar>

      <div style={{
        padding: '16px',
        width: '100%',
        boxSizing: 'border-box'
      }}>
        <Form
          form={form}
          layout='vertical'
          onFinish={onFinish}
          style={{
            backgroundColor: 'white',
            borderRadius: '12px',
            padding: '16px',
            boxShadow: '0 2px 8px rgba(0,0,0,0.05)',
            width: '100%',
            boxSizing: 'border-box'
          }}
          footer={
            <Button
              loading={submitting}
              block
              style={{
                backgroundColor: THEME_COLORS.primary,
                borderRadius: '24px',
                marginTop: '24px',
                height: '44px',
                color: 'white',
                fontSize: '16px',
                fontWeight: 'bold',
                border: 'none',
                boxShadow: '0 2px 8px rgba(27, 188, 155, 0.3)'
              }}
              onClick={form.submit}
            >
              发布游记
            </Button>
          }
        >
          <Form.Item
            name='title'
            rules={[{ required: true, message: '请输入游记标题' }]}
            extra={formError.title ? <div style={{ color: '#ff4d4f', fontSize: '12px', marginTop: '4px' }}>{formError.title}</div> : null}
          >
            <div>
              <div style={{
                marginBottom: '8px',
                display: 'flex',
                alignItems: 'center',
                fontSize: '15px'
              }}>
                <span style={{ color: '#f56c6c' }}>*</span>
                <span style={{ color: THEME_COLORS.text, marginLeft: '4px' }}>标题</span>
              </div>
              <Input
                placeholder='请输入一个吸引人的标题'
                style={{
                  '--font-size': '15px',
                  '--color': THEME_COLORS.text,
                  '--placeholder-color': '#bbb',
                  border: 'none',
                  borderBottom: '1px solid #eee',
                  borderRadius: '0',
                  paddingLeft: '0',
                  paddingRight: '0',
                  height: '46px',
                }}
              />
            </div>
          </Form.Item>

          <Form.Item
            name='location'
            style={{ marginTop: '28px' }}
          >
            <div>
              <div style={{
                marginBottom: '8px',
                color: THEME_COLORS.text,
                fontSize: '15px'
              }}>
                位置
              </div>
              <div style={{ position: 'relative' }}>
                <Input
                  placeholder='添加旅行地点 (选填)'
                  style={{
                    '--font-size': '15px',
                    '--color': THEME_COLORS.text,
                    '--placeholder-color': '#bbb',
                    border: 'none',
                    borderBottom: '1px solid #eee',
                    borderRadius: '0',
                    paddingLeft: '24px',
                    paddingRight: '0',
                    height: '42px',
                  }}
                />
                <EnvironmentOutline style={{
                  position: 'absolute',
                  left: 0,
                  top: '50%',
                  transform: 'translateY(-50%)',
                  color: THEME_COLORS.accent,
                  fontSize: '18px'
                }} />
              </div>
            </div>
          </Form.Item>

          <Form.Item
            name='content'
            rules={[{ required: true, message: '请输入游记内容' }]}
            extra={formError.content ? <div style={{ color: '#ff4d4f', fontSize: '12px', marginTop: '4px' }}>{formError.content}</div> : null}
            style={{ marginTop: '28px' }}
          >
            <div>
              <div style={{
                marginBottom: '8px',
                display: 'flex',
                alignItems: 'center',
                fontSize: '15px'
              }}>
                <span style={{ color: '#f56c6c' }}>*</span>
                <span style={{ color: THEME_COLORS.text, marginLeft: '4px' }}>内容</span>
              </div>
              <TextArea
                placeholder='分享你的旅行故事、感受、攻略或建议...'
                rows={6}
                maxLength={2000}
                showCount
                style={{
                  '--font-size': '15px',
                  '--color': THEME_COLORS.text,
                  '--placeholder-color': '#bbb',
                  border: '1px solid #eee',
                  borderRadius: '8px',
                  padding: '12px',
                  backgroundColor: 'rgba(249, 249, 249, 0.5)'
                }}
              />
            </div>
          </Form.Item>

          <div style={{
            marginTop: '28px',
            position: 'relative'
          }}>
            <div style={{
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              marginBottom: '12px'
            }}>
              <div style={{
                fontSize: '15px',
                color: THEME_COLORS.text,
                display: 'flex',
                alignItems: 'center'
              }}>
                <span style={{ color: '#f56c6c' }}>*</span>
                <span style={{ color: THEME_COLORS.text, marginLeft: '4px' }}>图片</span>
              </div>
              <span style={{
                fontSize: '13px',
                color: THEME_COLORS.lightText
              }}>
                {images.length}/9
              </span>
            </div>

            <div style={{
              fontSize: '14px',
              color: THEME_COLORS.lightText,
              marginBottom: '12px'
            }}>
              添加精美的照片能让游记更加生动
            </div>

            <ImageUploader
              value={images}
              onChange={setImages}
              upload={handleImageUpload}
              style={{
                '--cell-size': '90px',
                '--gap': '8px',
              }}
              {...imageUploaderProps}
            >
              <div style={{
                width: '90px',
                height: '90px',
                borderRadius: '8px',
                backgroundColor: 'white',
                border: `1px dashed ${THEME_COLORS.primary}`,
                display: 'flex',
                flexDirection: 'column',
                justifyContent: 'center',
                alignItems: 'center',
                color: THEME_COLORS.primary
              }}>
                <PictureOutline style={{ fontSize: '24px' }} />
                <span style={{ fontSize: '12px', marginTop: '4px' }}>上传图片</span>
              </div>
            </ImageUploader>

            {formError.images && (
              <div style={{
                color: '#ff4d4f',
                fontSize: '12px',
                marginTop: '8px'
              }}>
                {formError.images}
              </div>
            )}
          </div>

          <div style={{
            marginTop: '28px',
            position: 'relative'
          }}>
            <div style={{
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              marginBottom: '12px'
            }}>
              <div style={{ fontSize: '15px', color: THEME_COLORS.text }}>视频</div>
              {video && <span style={{ fontSize: '13px', color: THEME_COLORS.lightText }}>1/1</span>}
            </div>

            <div style={{
              fontSize: '14px',
              color: THEME_COLORS.lightText,
              marginBottom: '12px'
            }}>
              添加视频可以让游记更加精彩（可选）
            </div>

            {!video ? (
              <ImageUploader
                value={video ? [video] : []}
                onChange={files => setVideo(files[0])}
                upload={handleVideoUpload}
                style={{
                  '--cell-size': '90px',
                  '--gap': '8px',
                }}
                {...videoUploaderProps}
              >
                <div style={{
                  width: '90px',
                  height: '90px',
                  borderRadius: '8px',
                  backgroundColor: 'white',
                  border: `1px dashed ${THEME_COLORS.secondary}`,
                  display: 'flex',
                  flexDirection: 'column',
                  justifyContent: 'center',
                  alignItems: 'center',
                  color: THEME_COLORS.secondary
                }}>
                  <VideoOutline style={{ fontSize: '24px' }} />
                  <span style={{ fontSize: '12px', marginTop: '4px' }}>上传视频</span>
                </div>
              </ImageUploader>
            ) : (
              <div style={{
                position: 'relative',
                width: '100%',
                borderRadius: '8px',
                overflow: 'hidden',
                boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
              }}>
                <video
                  src={video.url}
                  controls
                  style={{ width: '100%', height: 'auto', borderRadius: '8px' }}
                />
                <Button
                  style={{
                    position: 'absolute',
                    top: '8px',
                    right: '8px',
                    width: '28px',
                    height: '28px',
                    borderRadius: '50%',
                    backgroundColor: 'rgba(0,0,0,0.5)',
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center',
                    padding: 0,
                    color: 'white',
                    border: 'none'
                  }}
                  onClick={() => setVideo(null)}
                >
                  <CloseOutline style={{ fontSize: '16px' }} />
                </Button>
              </div>
            )}
          </div>

          <div style={{
            marginTop: '24px',
            fontSize: '12px',
            color: THEME_COLORS.lightText,
            textAlign: 'center'
          }}>
            发布内容将在审核通过后显示
          </div>
        </Form>
      </div>
    </div>
  );
};

export default PublishPage;